package simple_bbs.endpoint;

import act.app.ActionContext;
import act.controller.Controller;
import act.event.OnEvent;
import act.social.SocialProfile;
import org.osgl.aaa.NoAuthentication;
import org.osgl.http.H;
import org.osgl.mvc.annotation.Action;
import simple_bbs.model.User;

@NoAuthentication
public class LoginController extends Controller.Util {

    /**
     * Handle a social login
     * @param profileFetchedEvent a social profile
     * @param userDao user DAO
     * @param context context
     */
    @OnEvent
    public void handleSocialLogin(
            SocialProfile.Fetched profileFetchedEvent,
            User.Dao userDao,
            ActionContext context
    ) {
        SocialProfile profile = profileFetchedEvent.source();
        String email = profile.getEmail();
        User user = userDao.findByEmail(email);
        if (null == user) {
            // register new user
            user = new User(profile);
            userDao.save(user);
        }
        context.login(user.email);
    }


    @Action("/logout")
    public void logout(H.Session session) {
        session.clear();
        redirect("/");
    }

}
